package com.jbt.mds.obdsdk

import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.jbt.mds.obdsdk.extension.SPUtils

class UserFragment:  Fragment() {

    lateinit var rView: View

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?  {
        super.onCreate(savedInstanceState)
        rView = View.inflate(context, R.layout.fg_user, null)
        return rView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //adapter与 数据的加载
        initListener()
        initData()
    }

    private fun initData() {

    }

    private fun initListener() {
        rView.findViewById<View>(R.id.ll_sbxx).setOnClickListener {
            startActivity(Intent(requireActivity(),DeviceInfoActivity::class.java))
        }

        rView.findViewById<View>(R.id.ll_sj).setOnClickListener {
            startActivity(Intent(requireActivity(),UpdateActivity::class.java))
        }

        // 退出当前账号点击事件
        rView.findViewById<View>(R.id.ll_tc).setOnClickListener {
            showLogoutDialog()
        }
    }

    private fun showLogoutDialog() {
        AlertDialog.Builder(requireContext())
            .setTitle("退出登录")
            .setMessage("确定要退出当前账号吗？")
            .setPositiveButton("确定") { _, _ ->
                logout()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun logout() {
        try {
            // 清除保存的token
            SPUtils.setString("token", "")
            
            // 跳转到登录页面
            val intent = Intent(requireContext(), LoginActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
            
            // 结束当前Activity
            requireActivity().finish()
        } catch (e: Exception) {
            e.printStackTrace()
            // 如果出现异常，尝试简单的跳转
            try {
                val intent = Intent(requireContext(), LoginActivity::class.java)
                startActivity(intent)
                requireActivity().finish()
            } catch (e2: Exception) {
                e2.printStackTrace()
            }
        }
    }
}